<?php

namespace App\Http\Controllers;

use App\Models\Config;
use App\Models\Cover;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class CoverController extends Controller
{
    public function index(Request $request)
    {
        $pageIndex = $request->get('pageIndex');
        $pageSize = $request->get('pageSize');
        $user = $request->user();

        $covers = Cover::query()->where('user_id',$user->id)
            ->orderByDesc('created_at')
            ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);

        return $this->response($covers,'成功');
    }

    //
    public function store(Request $request)
    {
        try{
            $validator = Validator::make($request->all(),[
                'name' => 'required|string',
                'category_id' => 'required|integer',
                'category_name' => 'required|string',
                'image' => 'required|string',
                'images' => 'required|array',
                'mode'  => 'required|integer',
                'tags'  => 'required|string'
            ]);

            if ($validator->fails()){
                return $this->response([],$validator->errors(),500);
            }

            $config = Config::query()->where('key','writeExam')->first();
            if (!$config) $writeExam = false;
            else $writeExam = $config->val;

            $data = $validator->validated();
            $data['images'] = join(',',$data['images']);
            $data['view'] = 0;
            $data['zan'] = 0;
            $data['coll'] = 0;
            $data['status'] = $writeExam ? 0 : 1;
            $data['user_id'] = $request->user()->id;

            Cover::query()->create($data);

            return $this->response([],'成功');
        }catch (\Exception $exception){
            return $this->response([],$exception->getMessage(),500);
        }
    }

    public function show($id)
    {
        try{
            return $this->response(Cover::query()->find($id));
        }catch (\Exception $exception){
            return $this->response([],$exception->getMessage());
        }
    }

    public function destroy($id)
    {
        $cover = Cover::query()->find($id);

        $path = Cover::url2path($cover->image);
        Storage::disk('public')->delete($path);

        $paths = collect($cover->images)->map(function ($image){
            return Cover::url2path($image);
        })->toArray();

        Storage::disk('public')->delete($paths);

        $cover->delete();

        return $this->response([],'删除成功');
    }

    public function search_cover(Request $request)
    {
        $pageIndex = $request->post('pageIndex');
        $pageSize = $request->post('pageSize');

        $list = [];

        if ($categoryName = $request->post('category_name')){
            $list = (new Cover)->queryByCategoryName($categoryName, $pageIndex, $pageSize);
        }

        if ($tags = $request->post('tags')){
            $list = (new Cover)->queryByTags($tags, $pageIndex, $pageSize);
        }

        if ($tags = $request->post('order_name')){
            $list = (new Cover)->queryByOrderName($tags, $pageIndex, $pageSize);
        }

        if ($search = $request->post('search')){
            $list = (new Cover)->queryByKeyword($search, $pageIndex, $pageSize);
        }

        return $this->response($list);
    }

    public function addview($id)
    {
        try{
            Cover::query()->where('id',$id)->increment('view');
        }catch (\Exception $exception){
            return $this->response([],$exception->getMessage());
        }

        return $this->response();
    }

    public function count()
    {
        $count = Cover::query()->count();
        return $this->response(['count' => $count]);
    }

    public function covers(Request $request)
    {
        $pageIndex = $request->get('pageIndex');
        $pageSize = $request->get('pageSize');
        $userId = $request->get('userId');
        $status = $request->get('status');

        if ($userId){
            if ($status == 'all') {
                $covers = Cover::query()
                    ->where('user_id',$userId)
                    ->orderByDesc('created_at')
                    ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
            }else{
                $covers = Cover::query()
                    ->where('user_id',$userId)
                    ->where('status',$status)
                    ->orderByDesc('created_at')
                    ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
            }
        }else{
            if ($status == 'all') {
                $covers = Cover::query()
                    ->orderByDesc('created_at')
                    ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
            }else{
                $covers = Cover::query()
                    ->where('status',$status)
                    ->orderByDesc('created_at')
                    ->paginate($pageSize, ['*'], 'pageIndex', $pageIndex);
            }

        }

        return $this->response($covers,'成功');
    }

    public function examine($id, Request $request)
    {
        $status = $request->input('status');
        $examine = $request->input('examine');

        $cover = Cover::query()->where('id', $id)->first();

        if (!$cover) return $this->response([],'作品未找到',500);

        $cover->status = $status;
        $cover->examine = $examine ?? '';
        $cover->save();

        return $this->response($cover,'成功');
    }
}
